package org.example.myleet.p435;

import java.util.Arrays;
import java.util.Comparator;

public class Solution {
    /**
     * O(n)
     * 2 ms
     */
    public int eraseOverlapIntervals(int[][] intervals) {
        if (intervals.length < 2) {
            return 0;
        }
        Arrays.sort(intervals, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                if (o1[0] == o2[0]) {
                    return o1[1] - o2[1];
                }
                return o1[0] - o2[0];
            }
        });
        int removeCount = 0;
        for (int i=0;i<intervals.length-1;i++) {
            if (intervals[i][1] > intervals[i + 1][0] && intervals[i][0] <= intervals[i + 1][0]) {
                //有交集，至少要移除掉一个区间
                removeCount++;
                if (intervals[i][1] > intervals[i + 1][1]) {
                    //较大的区间去掉，删除掉i区间
                    System.out.println("remove " + intervals[i][0] + "_" + intervals[i][1]);
                } else {
                    //较大的区间去掉
                    System.out.println("remove " + intervals[i+1][0] + "_" + intervals[i+1][1]);
                    //把i区间放到i+1位置，相当于删除掉i+1区间
                    intervals[i+1][0] = intervals[i][0];
                    intervals[i+1][1] = intervals[i][1];
                }
            }
        }
        return removeCount;
    }
}
